package app.controllers.help;

import app.Const;
import app.models.basic.HelpContent;
import app.models.basic.HelpNav;
import com.google.common.base.Strings;
import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.GET;
import com.jfinal.ext.interceptor.POST;
import goja.mvc.Controller;
import goja.rapid.datatables.DTCriterias;
import goja.rapid.db.Condition;

import java.util.UUID;

/**
 * <p>
 * 帮助对应的内容
 * </p>
 *
 * @author liuhui
 * @version 1.0
 * @since JDK 1.6
 */
public class ContentController extends Controller{
    /**
     * The index route.
     * the url /notice
     * the view in index.ftl.html
     */
    @Before(GET.class)
    public void index() {
        //帮助导航id
        String help_id = getPara(0, "0");
        setAttr("help_id",help_id);
    }

    /**
     * 列表访问
     */
    @Before(GET.class)
    public void dtlist() {
        String help_id = getPara(0, "0");
        final DTCriterias criterias = DTCriterias.criteriasWithRequest(getRequest());
        criterias.setParam("nav", Condition.EQ ,help_id);
        renderDataTables(criterias, "helpcontent");
    }

    @Before(GET.class)
    public void create() {
        String nav_id = getPara(0, "0");
        HelpNav helpNav = HelpNav.dao.findById(nav_id);
        HelpContent content = new HelpContent();
        content.set("nav",helpNav.getStr("id"));
        content.put("nav_name",helpNav.getStr("title"));
        setAttr(Const.ACTION_ATTR, Const.CREATE_ACTION);
        setAttr("content", content);
        render("item.ftl");
    }

    @Before(GET.class)
    public void edit() {
        String id = getPara(0, "0");
        HelpContent content = HelpContent.dao.findDetailById(id);
        setAttr(Const.ACTION_ATTR, Const.EDIT_ACTION);
        setAttr("content",content);
        render("item.ftl");
    }

    @Before(POST.class)
    public void save() {
        HelpContent content = getModel(HelpContent.class, "content");
        String helpNav = content.getStr("nav");
        if (Strings.isNullOrEmpty(content.getStr("id"))) {
            content.set("id", UUID.randomUUID().toString().replace("-", ""));
            content.save();
        } else {
            content.update();
        }
        redirect("/help/content/" + content.getStr("nav"));
    }

    public void delete(){
        String id = getPara(0, "0");
        boolean status = HelpContent.dao.deleteById(id);
        if(status){
            renderAjaxSuccess();
        }else {
            renderAjaxFailure();
        }
    }

}
